package com.flycent.hqhs.ui;

import java.lang.ref.WeakReference;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;

import com.flycent.hqhs.App;
import com.flycent.hqhs.Constants;
import com.flycent.hqhs.R;
import com.flycent.hqhs.UserBaseInfo;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.SimpleTitleBar;
import com.flycent.hqhs.util.ContextUtil;
import com.flycent.hqhs.util.PreferenceUtil;
import com.flycent.hqhs.util.StringUtil;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 注册
 * @author fbl
 */
@SuppressLint("HandlerLeak") 
public class RegisterActivity extends BackableTitleBarActivity{
	@ViewInject(id = R.id.register_name_edit) EditText mRegisterNameEdit;
	@ViewInject(id = R.id.register_pwd_edit) EditText mRegisterPwdEdit;
	@ViewInject(id = R.id.verify_edit) EditText mVerifyEdit;
	@ViewInject(id = R.id.verify_text_img) WebView mVerifyweb;
	@ViewInject(id = R.id.refreshImg , click = "butClick") ImageView mRefreshImg;
	@ViewInject(id = R.id.register_but , click = "butClick") Button mRegisterBut;
	@ViewInject(id = R.id.reg_if_check , click = "butClick") ImageView mRegisterCheckImg;
	@ViewInject(id = R.id.register_manual , click = "butClick") TextView mRegisterManualText;


	public static RegisterActivity instance = null;
	private String mUniqueId;
	private Boolean ifCheck = true;
	private Handler mHandler = new MyHandler(this);

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_register);
		FinalActivity.initInjectedView(this);
		instance = this;

		mUniqueId = getMyUUID();

		doRefreshImage();

		setEditFocusChangeLister();
	}

	private void setEditFocusChangeLister() {

		/*监听用户名EditText失去焦点的时候判断用户名是否符合规定 */
		mRegisterNameEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(!hasFocus){
					if(invalidateText(mRegisterNameEdit)){
						mRegisterNameEdit.setError(getString(R.string.info_please_input_user_no));
						return;
					}
					if( !(StringUtil.isPhoneNo(getText(mRegisterNameEdit)) 
							|| StringUtil.isEmail(getText(mRegisterNameEdit)) ) ){
						mRegisterNameEdit.setError(getString(R.string.txt_info_true_username_no));
						return;
					}
					//判断用户名是否存在
					checkUserName();
				}
			}
		});

		mRegisterPwdEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if( !hasFocus ){
					if(invalidateText(mRegisterPwdEdit)){
						mRegisterPwdEdit.setError(getString(R.string.info_please_input_pwd_no));
						return;
					}
					if( getText(mRegisterPwdEdit).length() < 6 || getText(mRegisterPwdEdit).length() > 32){
						mRegisterPwdEdit.setError(getString(R.string.info_please_input_pwd_no_length));
						return;
					}

				}
			}
		});

	}

	public void butClick(View v){

		//  刷新图片
		if(v == mRefreshImg){
			doRefreshImage();
			mVerifyEdit.setText("");
		}

		//
		if( v == mRegisterBut){
			doRegisterJudge();
		}
		//
		if( v == mRegisterCheckImg ){

			if(ifCheck){
				mRegisterCheckImg.setImageResource(R.drawable.reg_check_one);
				ifCheck = false;
			}else{
				mRegisterCheckImg.setImageResource(R.drawable.reg_checkin_one);
				ifCheck = true;
			}
		}
		//
		if( v == mRegisterManualText){
			ContextUtil.startActivity(this, RegisterManualActivity.class);
		}
	}



	/* 先检测用户名是否已经存在 */
	private void checkUserName() {

		new Thread(){
			public void run() {
				try {
					WebClient.getInstance(RegisterActivity.this).checkUsername(getText(mRegisterNameEdit));

				} catch (WebException e) {
					mHandler.sendEmptyMessage(0); //通知用户名已存在
				}
			}
		}.start();

	}

	private void doRegisterJudge() {
		if(invalidateText(mRegisterNameEdit,R.string.info_please_input_user_no)
				|| invalidateText(mRegisterPwdEdit,R.string.info_please_input_pwd_no)
				|| invalidateText(mVerifyEdit,R.string.txt_info_verify_no)
				){
			return;
		}
		if( !(StringUtil.isPhoneNo(getText(mRegisterNameEdit)) 
				|| StringUtil.isEmail(getText(mRegisterNameEdit)) ) ){
			App.showShortToast(getString(R.string.txt_info_true_username_no));
			return;
		}
		if( !ifCheck){
			App.showShortToast(getString(R.string.txt_info_check));
			return;
		}
		doRegisterRequest();
	}

	/**
	 * 注册请求
	 */
	private void doRegisterRequest() {
		showLoadingDialog("");
		new Thread(){
			public void run() {
				try {
					WebClient.getInstance(RegisterActivity.this).register(mUniqueId, getText(mVerifyEdit),  getText(mRegisterNameEdit), getText(mRegisterPwdEdit));
					mHandler.sendEmptyMessage(1);
				} catch (WebException e) {
					e.printStackTrace();
					mHandler.sendEmptyMessage(2);
				}

			};
		}.start();
	}

	private class MyHandler extends Handler{

		private WeakReference<Activity> mActivity;

		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){

				switch (msg.what) {
				case 0:
					//用户名已存在
					mRegisterNameEdit.setError(getString(R.string.info_please_input_user_is_exist));

					break;
				case 1:
					//注册成功
					App.showShortToast(getString(R.string.register_success));

					dologin();
					dismissLoadingDialog();
					finish();
					break;
				case 2:
					//注册失败
					dismissLoadingDialog();
					break;
				case 3:
					dismissLoadingDialog();
					LoginActivity.instance.finish();
					break;

				default:
					break;
				}

			}

		}

	}


	private void dologin() {
		showLoadingDialog("");
		new Thread(){
			public void run() {
				try {
					UserBaseInfo user = WebClient.getInstance(RegisterActivity.this).login(getText(mRegisterNameEdit), getText(mRegisterPwdEdit));
					PreferenceUtil.setUser(RegisterActivity.this, user);
					mHandler.sendEmptyMessage(3);
				} catch (WebException e) {
					e.printStackTrace();
					mHandler.sendEmptyMessage(2);
				}
			};
		}.start();

	}


	private void doRefreshImage() {
		String imgUri = Constants.IP+Constants.INFO.CAPTCHAIMAGE+mUniqueId;
		//直接用webview来显示图片，用image显示的话因为有缓存，不会刷新
		mVerifyweb.loadUrl(imgUri);

	}

	@Override
	protected void onTitleBarCreated(SimpleTitleBar titleBar) {
		super.onTitleBarCreated(titleBar);
		titleBar.setTitle(R.string.title_register);

		titleBar.setRightButtonText(R.string.title_login);
		titleBar.setOnRightButtonClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}


}
